//
//  MineViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "MineViewController.h"
#import "MineDetailViewController.h"
#import "MineAboutUsViewController.h"
#import "MineMianViewController.h"

#define kCachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic ,strong) UITableView *mineTableView;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) NSArray *imageArray;

@property (nonatomic, strong) UIView *titleView;

@property (nonatomic, strong) UIImageView *backImage;

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
   
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
     [self.mineTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:(UITableViewRowAnimationNone)];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
  //  self.navigationController.navigationBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self setNavigationBar];
//    self.navigationController.navigationBar.barTintColor = [[UIColor colorWithWhite:0.900 alpha:1.000] colorWithAlphaComponent:0.5];

    [self creatUpData];
    [self addSubViews];
}

- (void)setNavigationBar
{
    self.navigationItem.title = @"我的";
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"mine_navbar.jpg"] forBarMetrics:(UIBarMetricsDefault)];
    
   
  
}

- (void)creatUpData
{
    NSArray *arr1 = @[@"我的收藏", @"清除缓存", @"免责声明"];
    NSArray *arr2 = @[@"意见反馈", @"当前版本", @"关于我们"];
    self.dataArray = @[arr1, arr2];
    NSArray *img1 = @[@"mine_save", @"mine_clear", @"mine_mian.jpg"];
    NSArray *img2 = @[@"mine_edit", @"mine_new", @"mine_about"];
    self.imageArray = @[img1, img2];
}

- (void)addSubViews
{
    UIImageView *backgroundImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    backgroundImg.image = [UIImage imageNamed:@"MineBackGround.jpg"];
    backgroundImg.userInteractionEnabled = YES;
    [self.view addSubview:backgroundImg];
    
    
    self.mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:(UITableViewStyleGrouped)];
   
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
    self.backImage.image = [UIImage imageNamed:@"loginBack.jpg"];
    
    UIButton *imageButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    imageButton.frame = CGRectMake((self.backImage.width - 80) / 2, 30, 80, 80);
    imageButton.backgroundColor = [UIColor whiteColor];
    imageButton.layer.cornerRadius = 40;
    imageButton.layer.masksToBounds = YES;
    [imageButton setImage:[UIImage imageNamed:@"placeholderF.png"] forState:(UIControlStateNormal)];
    [self.backImage addSubview:imageButton];
    
    UIButton *loginButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginButton setTintColor:[UIColor colorWithRed:0.285 green:0.599 blue:1.000 alpha:1.000]];
    loginButton.frame = CGRectMake(imageButton.left, imageButton.bottom, imageButton.width, 30);
    [loginButton setTitle:@"立即登录" forState:(UIControlStateNormal)];
    [self.backImage addSubview:loginButton];
    
    self.mineTableView.tableHeaderView = self.backImage;
    self.mineTableView.dataSource = self;
    self.mineTableView.delegate = self;
    self.mineTableView.alpha = 0.8;
    self.mineTableView.bounces = NO;
    [backgroundImg addSubview:self.mineTableView];
}


#pragma mark -- UITableViewDataSource协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = self.dataArray[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.alpha = 2.0;
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.dataArray.count > 0) {
        NSArray *arr = self.dataArray[indexPath.section];
        NSString *str = arr[indexPath.row];
        NSArray *img = self.imageArray[indexPath.section];
        NSString *imgStr = img[indexPath.row];
        if (indexPath.section == 0 && indexPath.row == 1) {
            float size = [self folderSizeAtPath:kCachesPath];
            cell.textLabel.text = [NSString stringWithFormat:@"%@(%.2fM)", str, size];
        } else {
        cell.textLabel.text =str;
        }
        
        cell.textLabel.textColor = [UIColor blackColor];
        cell.imageView.image = [UIImage imageNamed:imgStr];
        if (indexPath.row == 1) {
           cell.accessoryType =  UITableViewCellAccessoryNone;
        } else {
             cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 10;
    } else
    {
        return 0;
    }
}

#pragma mark -- 跳转界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *arr = self.dataArray[indexPath.section];
    NSString *str = arr[indexPath.row];
    if ([str isEqualToString:@"我的收藏"]) {
        MineDetailViewController *detailVC = [[MineDetailViewController alloc] init];
        
        [self.navigationController pushViewController:detailVC animated:YES];
    } else if ([str isEqualToString:@"当前版本"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"当前版本1.0!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        // 实现0.3秒回收
        [self performSelector:@selector(actiondismissAlertView:) withObject:alert afterDelay:1.0];
        
    } else if ([str isEqualToString:@"意见反馈"]) {
        
        [self sendMail];
        
    } else if ([str isEqualToString:@"关于我们"]) {
        MineAboutUsViewController *aboutVC = [[MineAboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
        
    } else if ([str isEqualToString:@"免责声明"]) {
        MineMianViewController *mianVC = [[MineMianViewController alloc] init];
        mianVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mianVC animated:YES];
        
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定清楚缓存?" preferredStyle:(UIAlertControllerStyleAlert)];
        __block MineViewController *mySelf = self;
        // 创建按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
            [mySelf clearCache:kCachesPath];
            [mySelf.mineTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:(UITableViewRowAnimationNone)];
        }];
        // 创建按钮
        // 注意取消按钮只能添加一个
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }];
        
        
        [alert addAction:okAction];
        [alert addAction:cancelAction];
      
        [self presentViewController:alert animated:YES completion:nil];
       
    }
    
}

// 实现0.3秒回收
- (void)actiondismissAlertView:(UIAlertView *)alert
{
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

// 计算目录大小
- (float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize += [[SDImageCache sharedImageCache] getSize] /1024.0/1024.0;
     
        return folderSize;
    }
    return 0;
}

// 计算单个文件
- (float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

// 清理缓存文件
- (void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            //            if ([fileName isEqualToString:@"com.Lanou.OrangeAmusement"]) {
            //                break;
            //            }
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

- (void)sendMail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil) {
        // 首先检查当前设备支持邮件发送功能
        if ([mailClass canSendMail]) {
            [self displayMailComposerSheet];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"当前设备不支持发送邮件功能" message:nil delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles: nil];
            [alertView show];
        }
    }
    
}

#pragma mark ------ 发送邮件 ------
- (void)displayMailComposerSheet
{
    MFMailComposeViewController *emailPicker = [[MFMailComposeViewController alloc] init];
    emailPicker.mailComposeDelegate = self; // 设置emailPicker的代理为self
    
    [emailPicker setSubject:@"意见反馈"]; // 设置邮件正文
    
    // 设置收件人
    NSArray *toRecipients = @[@"15560101101@163.com"];

    [emailPicker setToRecipients:toRecipients]; // 设置收件人
      
    // 邮件正文
    NSString *emailBody = [NSString stringWithFormat:@"驴友帮,感谢你宝贵的反馈,我们会不断完善"];
    [emailPicker setMessageBody:emailBody isHTML:NO];
    
    [self presentViewController:emailPicker animated:YES completion:^{
    }];
}

#pragma mark ------ MFMailComposeViewControllerDelegate ------
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result) {
        case MFMailComposeResultCancelled:
        {
            [self alertWithMessage:@"取消邮件发送"];
            break;
        }
        case MFMailComposeResultSaved:
        {
            [self alertWithMessage:@"保存邮件成功"];
            
            break;
        }
        case MFMailComposeResultSent:
        {
            [self alertWithMessage:@"邮件发送成功"];
            
            break;
        }
        case MFMailComposeResultFailed:
        {
            [self alertWithMessage:@"邮件发送失败"];
            
            break;
        }
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)alertWithMessage:(NSString *)meesager {
    UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:meesager message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView1 show];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
